package com.caijb.juc;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author caijb
 * @version 1.0
 * @data 2025/10/29 19:15
 */
public class ReentrantReadWriteLockDemo {


    public static void main(String[] args) throws InterruptedException {
        int state = 0;
        int UNIT = 1 << 16;
        state += UNIT * 3;
        System.out.println("读锁个数：" + (state >>> 16));
        state += 50;
        System.out.println("写锁个数：" + (state & ((1 << 16) -1)));
        readAndWriteDemo();
    }

    private static void readAndWriteDemo() {
        ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
        ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
        new Thread(() -> {
            writeLock.lock();
            try {
                System.out.println("writeLock.lock()");
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                writeLock.unlock();
            }
        }, "Thread-write").start();
        new Thread(() -> {
            readLock.lock();
            try {
                System.out.println("readLock.lock()");
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                readLock.unlock();
            }
        }, "Thread-read").start();
    }
}
